package com.byit.aspect;

import com.alibaba.fastjson.JSONObject;
import com.byit.domain.SysBehaviorLog;
import com.byit.log.InterLog;
import com.byit.msg.MessageResult;
import com.byit.service.ISysBehaviorLogService;
import com.byit.utils.ServletUtil;
import com.byit.utils.ShiroUtils;
import com.byit.utils.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

@Aspect
@Component
@EnableAsync
public class InterLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(InterLogAspect.class);

    @Autowired
    private ISysBehaviorLogService behaviorLogService;

    // 配置织入点
    @Pointcut("@annotation(com.byit.log.InterLog)")
    public void logPointCut() {
    }

    /**
     * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "result")
    public void doBefore(JoinPoint joinPoint, Object result) {
        handleLog(joinPoint, null, result);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, (Object) null);
    }

    @Async
    protected void handleLog(final JoinPoint joinPoint, final Exception e, final Object result) {
        try {
            // 获得注解
            InterLog log = getAnnotationLog(joinPoint);
            if (log == null) {
                return;
            }
            insertLog(log, joinPoint, result, e);
        } catch (Exception exp) {
            // 记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    private void insertLog(InterLog log, JoinPoint joinPoint, Object result, Exception e) {
        SysBehaviorLog behaviorLog = new SysBehaviorLog();
        // 设置action动作
        behaviorLog.setOperType(log.operate());
        // 设置标题
        behaviorLog.setTitle(log.title());
        // 设置channel
        behaviorLog.setChannel(log.channel());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        behaviorLog.setMethod(className + "." + methodName + "()");

        behaviorLog.setOperTime(new Date());

        Map<String, String[]> map = ServletUtil.getRequest().getParameterMap();
        String params = JSONObject.toJSONString(map);

        logger.info("===========行为日志参数==========》" + params);

        behaviorLog.setOperParam(StringUtil.substring(params, 0, 255));

        behaviorLog.setOperAppCode(String.valueOf(map.get("appCode")));
        behaviorLog.setOperComCode(String.valueOf(map.get("comCode")));

        behaviorLog.setStatus("0");
        behaviorLog.setErrorMsg("操作成功!");

        if (null != result) {
            JSONObject mr = JSONObject.parseObject(result.toString());
            String code = String.valueOf(mr.get("code"));
            if (null != code && !"1".equals(code)) {
                behaviorLog.setStatus("2");
                behaviorLog.setErrorMsg(mr.getString("msg"));
            }
        }

        if (e != null) {
            behaviorLog.setStatus("1");
            behaviorLog.setErrorMsg(StringUtil.substring(e.getMessage(), 0, 2000));
        }

        // 请求的地址
        String ip = ShiroUtils.getIp();
        behaviorLog.setOperIp(ip);
        // 操作地点
        behaviorLog.setOperUrl(ServletUtil.getRequest().getRequestURI());

        behaviorLogService.insert(behaviorLog);
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private InterLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(InterLog.class);
        }
        return null;
    }
}